﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Service_monitoring.Utils.WindowsHelper
{
    internal class ScreenHelper
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern bool SystemParametersInfo(
             int uAction, int uParam, ref bool lpvParam,
             int flags);

        private const int SPI_GETSCREENSAVERRUNNING = 114; //获取是否处于屏保参数

        /// <summary>
        /// 桌面是否处于屏保
        /// </summary>
        /// <returns></returns>
        public static bool IsScreenSaverRunning()
        {
            bool isRunning = false;
            SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, ref isRunning, 0);
            return isRunning;
        }
    }
}

/// <summary>
/// 当前登录的用户变化（登录、注销和解锁屏）
/// </summary>
internal class SessionSwitchClass
{
    /// <summary>
    /// 解屏后执行的委托
    /// </summary>
    public Action SessionUnlockAction { get; set; }

    /// <summary>
    /// 锁屏后执行的委托
    /// </summary>
    public Action SessionLockAction { get; set; }

    public SessionSwitchClass()
    {
        SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
    }

    //析构，防止句柄泄漏
    ~SessionSwitchClass()
    {
        //Do this during application close to avoid handle leak
        SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
    }

    //当前登录的用户变化（登录、注销和解锁屏）
    private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
    {
        switch (e.Reason)
        {
            //用户登录
            case SessionSwitchReason.SessionLogon:
                BeginSessionUnlock();
                break;
            //解锁屏
            case SessionSwitchReason.SessionUnlock:
                BeginSessionUnlock();
                break;
            //锁屏
            case SessionSwitchReason.SessionLock:
                BeginSessionLock();
                break;
            //注销
            case SessionSwitchReason.SessionLogoff:
                break;
        }
    }

    /// <summary>
    /// 解屏、登录后执行
    /// </summary>
    private void BeginSessionUnlock()
    {
        Console.WriteLine("解屏");
        //解屏、登录后执行
    }

    /// <summary>
    /// 锁屏后执行
    /// </summary>
    private void BeginSessionLock()
    {
        Console.WriteLine("锁屏");
        //锁屏后执行
    }
}